package com.fanshuai.server2;

import com.fanshuai.frame.Message;
import com.fanshuai.net.SpringWebChatManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Slf4j
public class SpringWebChatServer extends TextWebSocketHandler {
    ObjectMapper mapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);

        log.info("connection init");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);

        String uid = SpringWebChatManager.getUid(session);
        SpringWebChatManager.delConnection(uid);
        if (StringUtils.isNotBlank(uid)) {
            groupSend(uid + "退出直播间");
        }

        log.info("connection closed");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String messageBody = message.getPayload();
        try {
            Message message1 = mapper.readValue(messageBody, Message.class);
            String uid = message1.getUid();

            switch (message1.getType()) {
                case 1:
                    groupSend(uid + "进入直播间");
                    SpringWebChatManager.addConnection(session, uid);
                    break;
                case 2:
                    groupSend(uid + "退出直播间");
                    SpringWebChatManager.delConnection(uid);
                    break;
                case 3:
                    String text = message1.getText();
                    groupSend(uid + ": " + text);
                    break;
            }
        } catch (Exception e) {
            log.error(e + "");
        }
    }

    private void groupSend(String text) {
        for (WebSocketSession session: SpringWebChatManager.sessionMap.values()) {
            try {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage(text));
                }
            } catch (Exception e) {
                log.error(e + "");
            }
        }
    }
}
